const path = require("path");
const express = require("express");
import createApp from "../app";
import { renderToString } from "vue/server-renderer";
import createRouter from "../router";
// 内存路由-> node用
import { createMemoryHistory } from "vue-router";
import { createPinia } from "pinia";

const server = express();

// server.use(express.static("build"));

server.use("/build", express.static("build")); // http://localhost:3000/build/client/client_bundle.js

server.get("/*", async (req, res) => {
  const app = createApp();
  let router = createRouter(createMemoryHistory());
  app.use(router);
  await router.push(req.url || "/"); // 等待路由加载完成
  await router.isReady(); // 等待路由加载完成

  // app 安装pinia插件
  const pinia = createPinia();
  app.use(pinia);

  const html = await renderToString(app); // 将vue实例渲染成html字符串
  res.send(
    `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <h1>Vue3 Serve Side Render</h1>
      <div id="app">
        ${html}
      </div>
    </body>
    </html>
    `
  );
});

server.listen(3000, () => {
  console.log("server is running at http://localhost:3000");
});
